# -*- encoding:utf-8 -*-
# __author__ = 'chenyongbing'
# __poject__ = 'ops_platform'
# __datetime__ = '2022/6/13'
# __name__ = 'tasks.py'
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from apps.system.handles import get_config_by_group
from utils.gitlab_helper import GL
from .models import GitCommit, GitCommitDayStat
import datetime
from django.db.models import Q

# Create your code here.

@shared_task
def gitlab_commit_history(refs=[], days=10):
    since = (datetime.datetime.today() - datetime.timedelta(days)).strftime('%Y-%m-%d')+ ' 00:00:00'
    until = (datetime.datetime.today() - datetime.timedelta(1)).strftime('%Y-%m-%d') + ' 23:59:59'
    params = get_config_by_group(group='gitlab')
    gl = GL(**params)
    datas = gl.get_all_commit_stat(refs=refs, since=since, until=until)
    for commitid, data in datas.items():
        obj, created = GitCommit.objects.update_or_create(commitid=data.get('commitid'), defaults=data)


@shared_task
def gitlab_commit_stat_by_user(days=10, maxrow=2000):
    since = (datetime.datetime.today() - datetime.timedelta(days)).strftime('%Y-%m-%d')
    # until = (datetime.datetime.today() - datetime.timedelta(1)).strftime('%Y-%m-%d')
    until = datetime.datetime.today().strftime('%Y-%m-%d')
    datas = {}
    queryset = GitCommit.objects.filter(Q(committed_date__range=[since, until], merge_date__isnull=True) | Q(merge_date__range=[since, until]))
    for commit in queryset:
        committer = commit.committer
        committed_date = commit.merge_date.strftime('%Y-%m-%d') if commit.merge_date else commit.committed_date.strftime('%Y-%m-%d')
        total = commit.total
        additions = commit.additions
        deletions = commit.deletions
        ref = commit.ref
        if additions > maxrow or deletions > maxrow: continue
        if committer not in datas.keys():
            datas[committer] = {}
        if committed_date not in datas[committer].keys():
            datas[committer][committed_date] = {}
        if ref not in datas[committer][committed_date].keys():
            datas[committer][committed_date][ref] = {}
        if 'total' not in datas[committer][committed_date][ref].keys():
            datas[committer][committed_date][ref]= {'total': 0, 'additions': 0, 'deletions': 0, 'committed_times': 0}

        datas[committer][committed_date][ref]['total']+=total
        datas[committer][committed_date][ref]['additions']+=additions
        datas[committer][committed_date][ref]['deletions']+=deletions
        datas[committer][committed_date][ref]['committed_times']+=1
    for committer, daydata in datas.items():
        for day, refdata in daydata.items():
            for ref, data in refdata.items():
            # data.update({'committer': committer, 'date': day})
                GitCommitDayStat.objects.update_or_create(committer=committer, ref=ref, date=day, defaults=data)